package com.sunny.ynhz.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sunny.ynhz.R;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.subscriber.ApiSubscriber;
import com.sunny.ynhz.bean.LoginBean;
import com.sunny.ynhz.bean.SecurityCodeBindingBean;
import com.sunny.ynhz.ui.MainActivity;
import com.sunny.ynhz.ui.base.AppBaseTranslationTitleBarActivity;
import com.sunny.ynhz.utils.AppManager;
import com.sunny.ynhz.utils.DeviceMsgUtils;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ShowUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by luao on 2017/7/27.
 */

public class SecurityCodeBindingActivity extends AppBaseTranslationTitleBarActivity {
    @BindView(R.id.phone_number)
    EditText phoneNumber;
    @BindView(R.id.securitycode)
    EditText securitycode;
    @BindView(R.id.get_security_code)
    TextView getSecurityCode;
    @BindView(R.id.ver_btn)
    Button verBtn;
    private Timer timer;
    private SecurityCodeBindingActivity activity;
    private int recLen = 10;
    private String phone;
    private String login_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_security_code_binding);
        ButterKnife.bind(this);
        activity = this;

        phone = SPUtil.get("phone", "null").toString();
        phoneNumber.setText(phone);
        login_name = SPUtil.get("login_name", "null").toString();


        phoneNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });

        securitycode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    @OnClick({R.id.get_security_code, R.id.ver_btn})
    public void onClick(View view) {
        if (view.getId() == R.id.get_security_code) {
            getCode(phone, login_name);
        } else if (view.getId() == R.id.ver_btn) {
            String loginname = SPUtil.get("login_name", "null").toString();
            String password = getIntent().getStringExtra("password");
            String imei = DeviceMsgUtils.getIMEI(activity);
            String code = securitycode.getText().toString();
            login(loginname, password, true, imei, code);
        }
    }

    private void click() {
        timer = new Timer();
        getSecurityCode.setClickable(false);
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {      // UI thread
                    @Override
                    public void run() {
                        recLen--;
                        getSecurityCode.setText("重新获取" + "(" + recLen + ")");
                        if (recLen <= 0) {
                            timer.cancel();
                            getSecurityCode.setText("获取验证码");
                            recLen = 10;
                            getSecurityCode.setClickable(true);
                        }
                    }
                });
            }
        };
        timer.schedule(task, 0, 1000);
    }


    private void getCode(String phone, String login_name) {
        HttpManager.getInstance()
                .getSecurityCode(phone, login_name)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiSubscriber(activity, new ApiSubscriber.HttpOnResultListener<SecurityCodeBindingBean>() {
                    @Override
                    public void onNext(SecurityCodeBindingBean jsonObject) {
                        click();
                        Toast.makeText(activity, jsonObject.getMsg(), Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onCompleted() {
                        ShowUtils.closePopwindow();
                    }

                    @Override
                    public void onstart() {
                        ShowUtils.disPlayProgress(activity);
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadOutFail();
                        super.onError(e);
                    }
                }));
    }

    private void login(final String username, String password, Boolean isSign, String devicecode, String securitycode) {
        HttpManager.getInstance()
                .login(username, password, isSign, devicecode, securitycode)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiSubscriber(this, new ApiSubscriber.HttpOnResultListener<LoginBean>() {
                    @Override
                    public void onNext(LoginBean jsonObject) {
                        //验证码过期
                        if (jsonObject.getCode() == 3) {

                        } else if (jsonObject.getCode() == 4) {
                            //验证码错误
                        } else if (jsonObject.getCode() == 1) {
                            Intent intent=new Intent(SecurityCodeBindingActivity.this,MainActivity.class);
                            intent.putExtra("type",1);
                            startActivity(intent);
                            AppManager.getInstance().finishActivity(SecurityCodeBindingActivity.class);
                            AppManager.getInstance().finishActivity(LoginActivity.class);
                        }
                        Toast.makeText(activity, jsonObject.getMsg(), Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onstart() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("err", e.toString());
                    }
                }));
    }
}
